import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

import { start, end } from "@/utils";

import { dynamicsRoutes } from "./main";
import { staticRoutes } from "./staticRoutes";

import { checkAuth } from "@/utils";
import { settingConfig } from "@/config";
import { db } from "@/storage";

/*
 * sort: number  --- > 对路由进行排序
 * hiddenInMenu: boolean  ---- > 是否在左侧菜单显示
 * icon: string  --- > 菜单icon ant-design-vue 自带的 icon 图标
 * svgIcon: streing   --- > 菜单icon   例如阿里下载下来的 svg 图标
 * key: string  --- > 与name相同  ---> 预留
 * notAuth string --- > true 不用权限
 * hiddenInBread boolean  ---> true 不在面包屑显示
 * notToken  boolean  --- > true  不需要token
 * name  string  ---- > 路由name。本系统的权限字段就是name，唯一鉴权key，且是缓存的唯一键值对，不可重复且必填！作为一种开发规范。
 * keepAlive: boolean  --- > 当前视图是否需要缓存
 */

const routes = [...dynamicsRoutes, ...staticRoutes];

/*
 * 重写路由， 捕获 err -- >  路由重复点击后报错问题
 *  解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
 */
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

const createRouter = () =>
    new VueRouter({
        scrollBehavior: () => ({ y: 0 }),
        routes,
    });

const router = createRouter();

// 重置路由
export function resetRouter() {
    const newRouter = createRouter();
    router.matcher = newRouter.matcher; // 重新设置路由的可匹配路径
}

const checkRouterAuth = (to) => {
    const auth = to.meta?.notAuth;
    const name = to.name || to.key;
    return auth || checkAuth(name);
};

const checkToken = (to) => {
    const needToken = to.meta?.notToken;
    if (!needToken) {
        const token = db.get("token");
        return token;
    } else {
        return true;
    }
};

router.beforeEach((to, from, next) => {
    start();
    if (!checkRouterAuth(to)) return next({ name: settingConfig.auth403Name });
    if (!checkToken(to)) return next({ name: settingConfig.loginName });
    next();
});

router.afterEach((to) => {
    end();
    window.scrollTo(0, 0);
});

export default router;

export * from "./main";
export * from './staticRoutes'
